package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.PickUpRecordMatterService;
import com.rzjm.exercise.module.service.PickUpRecordService;
import com.rzjm.exercise.module.service.ShopService;
import com.rzjm.exercise.module.service.ShopTypeRelationService;
import com.rzjm.exercise.sys.core.dict.domain.DictDO;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Controller
@RequestMapping(value = "/module/pickUpRecord",produces ="application/json;charset=UTF-8")
public class PickUpRecordController extends BaseController {
    @Resource
    private PickUpRecordService pickUpRecordService;
    @Resource
    private PickUpRecordMatterService pickUpRecordMatterService;
    @Resource
    private ShopService shopService;
    @Resource
    private ShopTypeRelationService shopTypeRelationService;

    @Log("查询物料页面")
    @GetMapping("")
    @RequiresPermissions("module:pickUpRecord:pickUpRecord")
    String pickUpRecord(Model model) {
        UserDO user = getUser();
        QueryWrapper<ShopTypeRelation> shopTypeRelationQw = new QueryWrapper<>();
        shopTypeRelationQw.eq("shop_type", 2);
        shopTypeRelationQw.eq("state", 1);
        List<ShopTypeRelation> shopTypeRelationList = shopTypeRelationService.list(shopTypeRelationQw);
        List<Integer> shopIds = shopTypeRelationList.stream().map(r -> r.getShopId()).collect(Collectors.toList());
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 1);
        wrapper.in("id", shopIds);
        if (user.getUserType() != 1 && user.getUserType() != 0){
            wrapper.eq("id",user.getShopId());
        }
//        if(user.getUserType() == 2){//集团管理员
//            wrapper.eq("group_id",user.getGroupId());
//        }else if(user.getUserType() == 3){//片区管理员
//            wrapper.eq("pianqu_id",user.getPianquId());
//        }else if(user.getUserType() == 4){//分厂管理员
//            wrapper.eq("shop_id",user.getShopId());
//        } else if(user.getUserType() == 10){//企业管理员
//            wrapper.eq("shop_id",user.getShopId());
//        }
        List<Shop> shopList = shopService.list(wrapper);
        model.addAttribute("shopList", shopList);
        return "module/pickUpRecord/list";
    }


    @Log("查询物料页面")
    @ResponseBody
    @GetMapping("/list")
    public DataTableLayUI<PickUpRecord> list(DataTableLayUI<PickUpRecord> condition) {
        Map<String, Object> searchParams = condition.getSearchParams();


        String shopId = searchParams.containsKey("shopId") ? searchParams.get("shopId").toString() : null;
        String keywords = searchParams.containsKey("search_like_realName") ? searchParams.get("search_like_realName").toString() : null;

        UserDO userDO = getUser();
        if (userDO.getUserType() != 1 && userDO.getUserType() != 0 && (userDO.getShopId() == null || userDO.getShopId() == 0)){
            return new DataTableLayUI<PickUpRecord>();
        }
        QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
        if(userDO.getUserType() != 1 && userDO.getUserType() != 0){
            searchParams.put("shopId", userDO.getShopId());
            qw.eq("shop_id", userDO.getShopId());
        }
        if(StrUtil.isNotEmpty(shopId)){
            searchParams.put("shopId", shopId);
            qw.eq("shop_id", shopId);
        }

        if(StrUtil.isNotEmpty(keywords)){
            qw.and(wrapper->{
                wrapper.like("real_name", keywords).or().like("phone_num",keywords);
            });
        }

        if (searchParams.get("beginTime") != null && StringUtils.isNotBlank(searchParams.get("beginTime").toString())) {
//            searchParams.put("beginTime", searchParams.get("beginTime").toString() + " 00:00:00");
            qw.ge("create_time", searchParams.get("beginTime").toString() + " 00:00:00");
        }
        if (searchParams.get("endTime") != null && StringUtils.isNotBlank(searchParams.get("endTime").toString())) {
//            searchParams.put("endTime", searchParams.get("endTime").toString() + " 23:59:59");
            qw.le("create_time", searchParams.get("endTime").toString() + " 23:59:59");
        }
        condition.setQw(qw);
        DataTableLayUI<PickUpRecord> dt = pickUpRecordService.pageSearchLayUI(condition);
        List<PickUpRecord> list = dt.getData();
        list.forEach(record->{
            Shop shop = shopService.findById(record.getShopId());
            if(shop!= null){
                record.setShopName(shop.getShopName());
            }
            List<PickUpRecordMatter> pickUpRecordMatterList = pickUpRecordMatterService
                    .selectListByColumn("pick_up_record_id", record.getId());
            if (pickUpRecordMatterList != null && pickUpRecordMatterList.size() > 0){
                String wuliaoName = pickUpRecordMatterList.stream().map(m -> m.getWuLiaoName()).collect(Collectors.joining(","));
                String wuliaoWeight = pickUpRecordMatterList.stream().map(m -> String.valueOf(m.getWuLiaoWeight()))
                        .collect(Collectors.joining(","));
                record.setWuLiaoNameStr(wuliaoName);
                record.setWuLiaoWeightStr(wuliaoWeight);
            }
        });
        return dt;
    }


    @Log("新增物料页面")
    @GetMapping("/add")
    @RequiresPermissions("module:pickUpRecord:add")
    String add(Model model) {
        PickUpMatter pickUpRecord = new PickUpMatter();
        model.addAttribute("pickUpRecord", pickUpRecord);
        return "module/pickUpRecord/detail";
    }

    @Log("编辑物料页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:pickUpRecord:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        PickUpRecord pickUpRecord = pickUpRecordService.findById(id);
        Shop shop = shopService.findById(pickUpRecord.getShopId());
        if (shop != null){
            pickUpRecord.setShopName(shop.getShopName());
        }
        if (pickUpRecord.getRecordType() != null && pickUpRecord.getRecordType() == 0){
            pickUpRecord.setRecordTypeStr("卸车");
        }else if (pickUpRecord.getRecordType() != null && pickUpRecord.getRecordType() == 1){
            pickUpRecord.setRecordTypeStr("装车");
        }
        if (pickUpRecord.getCreateTime() != null){
            pickUpRecord.setCreateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", pickUpRecord.getCreateTime()));
        }else {
            pickUpRecord.setCreateTimeStr("");
        }
        if (pickUpRecord.getCancelTime() != null){
            pickUpRecord.setCancelTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", pickUpRecord.getCancelTime()));
        }else {
            pickUpRecord.setCancelTimeStr("");
        }
        if (pickUpRecord.getBeginTime() != null && pickUpRecord.getEndTime() != null){
            pickUpRecord.setBeginTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", pickUpRecord.getBeginTime()));
            pickUpRecord.setEndTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", pickUpRecord.getEndTime()));
        }else {
            pickUpRecord.setBeginTimeStr("");
            pickUpRecord.setEndTimeStr("");
        }
        List<PickUpRecordMatter> pickUpRecordMatterList = pickUpRecordMatterService
                .selectListByColumn("pick_up_record_id", pickUpRecord.getId());
        if (pickUpRecordMatterList != null && pickUpRecordMatterList.size() > 0){
            String wuliaoName = pickUpRecordMatterList.stream().map(m -> m.getWuLiaoName()).collect(Collectors.joining(","));
            String wuliaoWeight = pickUpRecordMatterList.stream().map(m -> String.valueOf(m.getWuLiaoWeight()))
                    .collect(Collectors.joining(","));
            pickUpRecord.setWuLiaoNameStr(wuliaoName);
            pickUpRecord.setWuLiaoWeightStr(wuliaoWeight);
        }
        model.addAttribute("pickUpRecord", pickUpRecord);
        return "module/pickUpRecord/detail";
    }

    @Log("新增物料")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:pickUpRecord:add")
    public R save(@Valid PickUpRecord pickUpRecord) {
        UserDO user = getUser();
        pickUpRecord.setState(1);
        pickUpRecord.setShopId(user.getShopId());
        pickUpRecordService.save(pickUpRecord);
        return R.ok();
    }


    @GetMapping("/exportExcel")
    public void testExprotExcel1(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                 @RequestParam("shopId") String shopId,@RequestParam("realName") String realName,
                                 HttpServletRequest request, HttpServletResponse response){
        UserDO user = getUser();
        Map<String,Object> map = new HashMap<>();

        QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            map.put("begin_time", begin_date +" 00:00:00");
            map.put("end_time", end_date +" 23:59:59");
            qw.between("create_time",  begin_date +" 00:00:00", end_date +" 23:59:59");
        }
        if(user.getUserType() == 11){
            qw.eq("shop_id", user.getShopId());
        }else{
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shopId", shopId);
                qw.eq("shop_id", shopId);
            }
        }
        if(StrUtil.isNotEmpty(realName)){
            qw.and(wrapper->{
                wrapper.like("real_name", realName).or().like("phone_num",realName);
            });
        }

        List<PickUpRecord> records = pickUpRecordService.list(qw);
        records.forEach(record->{
            Shop shop = shopService.findById(record.getShopId());
            if(shop!= null){
                record.setShopName(shop.getShopName());
            }
//            装车类型 0 - 卸车 1 - 装车
            if(record.getRecordType() == 0){
                record.setRecordTypeStr("卸车");
            }else{
                record.setRecordTypeStr("装车");
            }
            record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));
            record.setBeginTimeStr(DateUtils.getTime(record.getBeginTime()));
            record.setEndTimeStr(DateUtils.getTime(record.getEndTime()));
            List<PickUpRecordMatter> pickUpRecordMatterList = pickUpRecordMatterService
                    .selectListByColumn("pick_up_record_id", record.getId());
            if (pickUpRecordMatterList != null && pickUpRecordMatterList.size() > 0){
                String wuliaoName = pickUpRecordMatterList.stream().map(m -> m.getWuLiaoName()).collect(Collectors.joining(","));
                String wuliaoWeight = pickUpRecordMatterList.stream().map(m -> String.valueOf(m.getWuLiaoWeight()))
                        .collect(Collectors.joining(","));
                record.setWuLiaoNameStr(wuliaoName);
                record.setWuLiaoWeightStr(wuliaoWeight);
            }
        });
        ExcelUtils.writeExcel(response, records, PickUpRecord.class, System.currentTimeMillis() + "_车辆预约记录.xlsx");
    }

    /**
     * 修改
     */
    @Log("更新物料")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:pickUpRecord:edit")
    public R update(@Valid PickUpRecord pickUpRecord) {
        UserDO user = getUser();
        pickUpRecord.setState(1);
        pickUpRecord.setShopId(user.getShopId());
        pickUpRecordService.updateById(pickUpRecord);
        return R.ok();
    }


    /**
     * 删除
     */
    @Log("删除物料")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("module:pickUpRecord:remove")
    public R remove(Integer id) {
        UpdateWrapper<PickUpRecord> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("state", 0);
        if (pickUpRecordService.update(wrapper)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @Log("取消预约")
    @PostMapping("/cancel")
    @ResponseBody
    @RequiresPermissions("module:pickUpRecord:edit")
    public R cancel(Integer id) {
        UpdateWrapper<PickUpRecord> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("is_cancel", 1);
        if (pickUpRecordService.update(wrapper)) {
            return R.ok();
        }
        return R.error();
    }
}
